package com.example.demo.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/add-two-numbers/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/03/11 9:48
 */
public class _2_两数相加 {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(9, new ListNode(9));
        ListNode listNode1 = new ListNode(9);
        ListNode listNode2 = addTwoNumbers(listNode1, listNode);
        System.out.println();
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        List<Integer> list = new ArrayList<>();
        while (l1 != null || l2 != null) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
            }
            if (l2 != null) {
                sum += l2.val;
            }
            carry = sum / 10;
            list.add(sum % 10);
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry != 0) {
            list.add(carry);
        }
        ListNode res = new ListNode(-1, null);
        ListNode temp = res;
        for (Integer integer : list) {
            temp.next = new ListNode(integer);
            temp = temp.next;
        }
        return res.next;
    }
}
